<%@ page language="java" contentType="text/html; charset=windows-1255"
    pageEncoding="windows-1255" %>
<%@ page import="com.optimus.db.DataBaseManager,com.optimus.model.mapped.ProductBean,
java.io.*,java.util.List,java.sql.ResultSet, com.optimus.dao.ProductDAO,
com.optimus.utils.SpringUtils"%>
<jsp:useBean id="customerUser" class="com.optimus.model.mapped.CustomerBean" scope="session"></jsp:useBean>
<jsp:setProperty property="*" name="customerUser"/>


<%@page import="java.util.Collections"%><html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <style type="text/css">
        body { font-family:Arial, Helvetica, Sans-Serif; font-size:0.8em; color: white;}
        #report { border-collapse:collapse;}
        #report h4 { margin:0px; padding:0px;}
        #report img { float:right;}
        #report ul { margin:10px 0 10px 40px; padding:0px;}
        #report th { background:#1d1d1d url(images/AdminImages/header_bkg.png) repeat-x scroll center left; color:#fff; padding:7px 15px; text-align:left;}
        #report td { background:#1d1d1d none repeat-x scroll center left; color:#FFF; padding:7px 15px; }
        #report tr.odd td { background:#FFFFFC url(images/AdminImages/row_bkg.png) repeat-x scroll center left; cursor:pointer; }
        #report div.arrow { background:transparent url(images/AdminImages/arrows.png) no-repeat scroll 0px -16px; width:16px; height:16px; display:block;}
        #report div.up { background-position:0px 0px;}
    </style>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">  
        $(document).ready(function(){
            $("#report tr:odd").addClass("odd");
            $("#report tr:not(.odd)").hide();
            $("#report tr:first-child").show();
            
            $("#report tr.odd").click(function(){
                $(this).next("tr").toggle();
                $(this).find(".arrow").toggleClass("up");
            });
            $("#report").jExpand();
        });
    </script> 
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1255">
          
</head>
<body style="background-color: #1d1d1d;">
<center>
<%
	if (!customerUser.isAdmin())
	{
		response.sendRedirect("unauthorized.jsp");
	}
	List<ProductBean> productsList = null;
	ProductDAO productDAO = (ProductDAO) SpringUtils.getBean("productDAO");

	if(request.getParameter("update")!=null )
	{
		   if(request.getParameter("update").equals("Update"))
		   {
			    ProductBean updateProduct = new ProductBean();
				updateProduct.setCategoryId(Integer.valueOf(request.getParameter("category_id")));
				updateProduct.setId(Integer.parseInt(request.getParameter("product_id")));
				updateProduct.setName(request.getParameter("product_name"));
				updateProduct.setPicturePath(request.getParameter("picture_location"));
				updateProduct.setPrice(Double.valueOf(request.getParameter("price")));
				updateProduct.setDescription(request.getParameter("description"));
				productDAO.updateIntoDB(updateProduct);
				out.println("Update process has been done successfully!");
		   }
	}
	if(request.getParameter("remove")!=null)
	{
	   if(request.getParameter("remove").equals("Remove"))
	   {
		   	productDAO.deleteProduct(Integer.parseInt(request.getParameter("product_id")));
		   	out.println("Remove process has been done successfully!");
	   }
	}
	
	if(request.getContentType()!=null)
	{
		String contentType = request.getContentType();
		if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0))
		{
			DataInputStream in = new DataInputStream(request.getInputStream());
			int formDataLength = request.getContentLength();

			byte dataBytes[] = new byte[formDataLength];
			int byteRead = 0;
			int totalBytesRead = 0;
			while (totalBytesRead < formDataLength)
			{
				byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
				totalBytesRead += byteRead;
			}

			String file = new String(dataBytes);
			
			String pName = "";
			String price = "";
			String categoryId = "";
			String productId = "";
			String saveFile = "";
			String serverPath = "";
			String sorcePath = "";
			String description = "";

			if(file.indexOf("productName")> -1)
			{
				pName = file.substring(file.indexOf("productName"));
				pName = pName.substring(pName.indexOf("\n")+3);
				pName = pName.substring(0,pName.indexOf("\r"));
			}
			if(file.indexOf("price")> -1)
			{
				price = file.substring(file.indexOf("price"));
				price = price.substring(price.indexOf("\n")+3);
				price = price.substring(0,price.indexOf("\r"));
			}
			
			if(file.indexOf("categoryId")> -1)
			{
				categoryId = file.substring(file.indexOf("categoryId"));
				categoryId = categoryId.substring(categoryId.indexOf("\n")+3);
				categoryId = categoryId.substring(0,categoryId.indexOf("\r"));
			}

			if(file.indexOf("description")> -1)
			{
				description = file.substring(file.indexOf("description"));
				description = description.substring(description.indexOf("\n")+3);
				description = description.substring(0,description.indexOf("\r"));
			}

			if(file.indexOf("id")> -1)
			{
				productId = file.substring(file.indexOf("id"));
				productId = productId.substring(productId.indexOf("\n")+3);
				productId = productId.substring(0,productId.indexOf("\r"));
			}
				saveFile = file.substring(file.indexOf("filename=\"") + 10);
				saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
				saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile
						.indexOf("\""));

			if(!saveFile.equals(""))
			{

				int lastIndex = contentType.lastIndexOf("=");
				String boundary = contentType.substring(lastIndex + 1, contentType.length());
				int pos;
				pos = file.indexOf("filename=\"");

				pos = file.indexOf("\n", pos) + 1;

				pos = file.indexOf("\n", pos) + 1;

				pos = file.indexOf("\n", pos) + 1;

				int boundaryLocation = file.indexOf(boundary, pos) - 4;
				int startPos = ((file.substring(0, pos)).getBytes()).length;
				int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
				String filePath = application.getRealPath("/images/uploadedFiles")+"\\"+ saveFile;
				System.out.print(filePath);
				FileOutputStream fileOut = new FileOutputStream(filePath);

				//fileOut.write(dataBytes);
				fileOut.write(dataBytes, startPos, (endPos - startPos));
				fileOut.flush();
				fileOut.close();
				//to do : update to database with specific id
				serverPath = "http://localhost:8080/OptimuStore/";
				sorcePath = "/images/uploadedFiles"+"//"+ saveFile;
				
			}
			else
			{
				%>
				<script type="text/javascript">
				alert("Please load picture");
				</script>
				<%				
			}
			
			if((!pName.equals("")) &&
			   (!price.equals("")) &&
			   (!categoryId.equals(""))&&
			   (!sorcePath.equals(""))&&
			   (!description.equals("")))
			{
				ProductBean newProduct = new ProductBean();
				newProduct.setCategoryId(Integer.valueOf(categoryId));
				newProduct.setName(pName);
				newProduct.setPrice(Double.valueOf(price));
				newProduct.setPicturePath(serverPath+sorcePath);
				newProduct.setDescription(description);
				productDAO.insertIntoDB(newProduct);			
			}
			else if((!productId.equals(""))&&(!sorcePath.equals("")))
			{
				productDAO.updateNewPictureIntoDB(Integer.valueOf(productId),serverPath+sorcePath);
			}
			else
			{
				%>
				<script type="text/javascript">
				alert("Please fill data in all fileds");
				</script>
				<%
			}
		}
	}
	
%>  
	
			<form action="#" method="post"">
			<label>Select product category:</label>
			  <SELECT name="categories" style="width: 170px; height:20px;">
               <OPTION value="0">All Categories</OPTION>
               <%
               List<String> columnList=null;
               List<String> parsedColumnList=null;               
               int numOfCategories = 
            	   SpringUtils.getDatabaseManager().getJdbcTemplate().queryForInt("SELECT COUNT(category_id) FROM category");
               for (int i=1;i<=numOfCategories;i++)
               {
            	   String categoryName = SpringUtils.getDatabaseManager().getJdbcTemplate().queryForObject("SELECT category_name FROM category WHERE category_id = "+i,String.class);
            	   out.print("<OPTION value=\""+i+"\">"+categoryName+"</OPTION>");
               }
               %>
          	 </SELECT>
          	 <label>&nbsp;&nbsp;&nbsp; Order By </label>
          	 <SELECT name="order" style="width: 170px; height:20px;">
          	 <%
          		columnList = SpringUtils.getDatabaseManager().getTableColumns("product");
          		parsedColumnList = SpringUtils.getDatabaseManager().parseColumnNames(columnList);
          		for(int i=0;i<columnList.size();i++)
          		{
          			out.print("<OPTION value=\""+columnList.get(i)+"\">"+parsedColumnList.get(i)+"</OPTION>");
          		}
          	 %>
             </SELECT>
		<input type="submit" value="Load Table From DB">
		 </form>
		
    <table id="report">
        <tr>
				<%				
				for(String column : parsedColumnList)
				{
					if (!column.equals("Description"))
					{
						out.print("<th>");
						out.print(column);				
						out.print("</th>");
					}
				}
				%>
            <th></th>
            <th></th>
            <th></th>
        </tr>
     	<%	
     		if((request.getParameter("categories") != null) && (request.getParameter("order") != null))
     		{
    	    	productsList = productDAO.selectAllProductsByCategory(Integer.valueOf(request.getParameter("categories")),request.getParameter("order"));
					for(ProductBean product : productsList)
					{
						out.print("<form action=\"#\" method=\"post\">");
						out.print("<tr>");
							out.print("<td>");
							out.print("<input type=\"text\" name =\""+columnList.get(0)+"\" readonly=\"readonly\" value =\""+product.getId()+"\" style=\"width: 30px;\"");
							out.print("</td>");
		
							out.print("<td>");
							out.print("<input type=\"text\" name =\""+columnList.get(1)+"\" value =\""+product.getName()+"\"");
							out.print("</td>");
		
							out.print("<td>");
							out.print("<input type=\"text\" name =\""+columnList.get(2)+"\" value =\""+product.getPrice()+"\" style=\"width: auto;\"");
							out.print("</td>");
		
							out.print("<td>");
							out.print("<input type=\"text\" name =\""+columnList.get(3)+"\" value =\""+product.getPicturePath()+"\" style=\"width: auto;\"");
							out.print("</td>");
			
							out.print("<td>");
							out.print("<select name=\""+columnList.get(4)+"\">");
			               for (int i=1;i<=numOfCategories;i++)
			               {
			            	   String selected = "";
			            	   String categoryName = SpringUtils.getDatabaseManager().getJdbcTemplate().queryForObject("SELECT category_name FROM category WHERE category_id = "+i,String.class);
			            	   if(product.getCategoryId()==i)
			            	   {
			            		   selected = "selected=\"selected\"";
			            	   }
			            	   out.print("<OPTION "+ selected +" value=\""+i+"\">"+categoryName+"</OPTION>");
			               }
			               out.print("</select>");
				  
							out.print("</td>");
	
							out.print("<td>");
							out.print("<input type=\"submit\" name =\"update\" value=\"Update\">");
							out.print("</td>");				
							out.print("<td>");				
							out.print("<input type=\"submit\" name =\"remove\" value=\"Remove\">");
							//out.print("</form>");
							out.print("</td>");
							out.print("</td>");
							out.print("<td><div class=\"arrow\"></div></td>");
						out.print("</tr>");
		
						%>
				        <tr>
				            <td colspan="5">
				                <img src="<%=product.getPicturePath()%>" width="150" />
				                <h4>Additional information</h4>
				                <ul>
				                    <li><b>Description:</b></li>
				                    <li><input type="text" name="description" value="<%=product.getDescription()%>" style="width: 120px;"/></li>
				                    <li><b>Image Location</b></li>
				                    <li><%=product.getPicturePath()%></li>
				                 </ul>
				                 </form>
				                 	<form action="#" method="post" enctype="multipart/form-data">
				                    <input type="hidden" name = "id" value="<%=product.getId() %>"/>
				                    <input type="file" name="loadFile"/>
				                    <input type="submit" name="upload" value="Upload">
				                    </form>
				                    
				            </td>
				            <td></td>
				            <td></td>
				            <td></td>
				        </tr>
				        <%}
     		}
				        %>
        <tr height="15"></tr>
   </table>
		<div id="Edit" style="font-style: italic;">
 	     	<form action="#" method="post" enctype="multipart/form-data">
				<label>Product Name:</label><input type="text" name="productName">
				<label>Price:</label> <input type="text" name="price">
				<label>category Id:</label>
				<%
				   out.print("<select name=\"categoryId\">");
	               for (int i=1;i<=numOfCategories;i++)
	               {
	            	   String categoryName = SpringUtils.getDatabaseManager().getJdbcTemplate().queryForObject("SELECT category_name FROM category WHERE category_id = "+i,String.class);
	            	   out.print("<OPTION value=\""+i+"\">"+categoryName+"</OPTION>");
	               }
	               out.print("</select>");
				
				%>
				<label>Description:</label><input type="text" name="description" >
			    <label>Select a file:</label> <input type="file" name="first" /> 
				<input type="submit" name="addProduct" value="Add Product To Catalog">
			</form>
		</div>
		<a href="index.jsp">Go back to the OptimuStore</a>
		</center>
</body>
</html>
